----------- 
-- Author: Bojun Chen
-- Date: 2021-09-14 13:39:27
-- Desc: 基础状态
----------- 



local BaseState = class("BaseState")


function BaseState:ctor()
    self.name = 'BaseState'
    self.transitions = {}
    self.stateMachine = nil
    self.transitionIdx = 1
    self.workingTransition = nil
end

--[[
    @desc: 进入本状态
    author:Bojun Chen
    time:2021-09-14 15:52:39
    --@preState: 本状态的上一个状态实例
    @return:
]]
function BaseState:OnEnter(preState)
    
end

--[[
    @desc: 退出本状态
    author:Bojun Chen
    time:2021-09-14 15:53:01
    --@nextState: 下一个状态
    @return:
]]
function BaseState:OnExit(nextState)
    
end

--[[
    @desc: 帧更新，当前状态进入时调用
    author:Bojun Chen
    time:2021-09-14 15:53:13
    @return:
]]
function BaseState:OnUpdate()
    self.workingTransition = self.transitions[self.transitionIdx]    
    if self.workingTransition ~= nil and self.workingTransition:OnCheck() then
        if self.workingTransition:OnCompleteCallBack() then
            self:DoTransition(self.workingTransition)
        end
    end
    
    self.transitionIdx = self.transitionIdx + 1
    if self.transitionIdx > #self.transitions then
        self.transitionIdx = 1
    end    
end

--[[
    @desc: 设置状态机
    author:Bojun Chen
    time:2021-09-14 15:52:14
    --@stateMachine: 本状态的状态机，持有上下文
    @return:
]]
function BaseState:SetStateMachine(stateMachine)
    self.stateMachine = stateMachine
end

--[[
    @desc: 添加转换
    author:Bojun Chen
    time:2021-09-14 15:54:10
    --@transition: 本状态的转换
    @return:
]]
function BaseState:AddTransition(transition)
    if transition == nil then
        LogWarning('transion is nil!')
        return
    end

    if transition.from ~= self.name then
        LogWarning('can not add this transition, becuse this state can not contain this transition!')
        return
    end

    if table.contain(self.transitions, transition) then
        LogWarning('can not add this transition, because this transition exist!')
        return
    end

    table.insert(self.transitions, transition)
end

--[[
    @desc: 执行转换
    author:Bojun Chen
    time:2021-09-14 16:11:14
    --@transition: 转换实例
    @return:
]]
function BaseState:DoTransition(transition)
    self.stateMachine:ChangeState(transition.toState)
end


return  BaseState